<template>
	<div class="report-page" style="padding: 20px">
		<!-- 顶部工具栏 -->
		<div class="toolbar">
			<el-radio-group v-model="areaType" size="small">
				<el-radio-button label="楼栋" />
				<el-radio-button label="楼层" />
				<el-radio-button label="区域" />
			</el-radio-group>

			<el-date-picker v-model="dateRange" type="daterange" size="small"
				style="width: 240px; margin-left: 10px;" />

			<el-radio-group v-model="activeType" size="small" style="margin-left: 10px">
				<el-radio-button label="电" />
				<el-radio-button label="水" />
				<el-radio-button label="气" />
			</el-radio-group>

			<el-button size="small" type="primary" style="margin-left: auto;" @click="exportExcel">导出 Excel</el-button>
			<el-button size="small" type="success" @click="exportImage">导出图片</el-button>
		</div>

		<!-- 图表 -->
		<v-chart ref="chartRef" :option="chartOptions" style="height: calc(100vh - 200px);" />
	</div>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue'
import VChart from 'vue-echarts'
import html2canvas from 'html2canvas'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'

const chartRef = ref(null)
const areaType = ref('楼栋')
const activeType = ref('电')
const dateRange = ref([new Date('2024-04-01'), new Date('2024-04-07')])

const areaLabels = {
	楼栋: ['A栋', 'B栋', 'C栋'],
	楼层: ['1F', '2F', '3F'],
	区域: ['东区', '西区', '南区']
}

// 根据选择动态生成模拟数据
const chartOptions = computed(() => {
	const labels = areaLabels[areaType.value]
	const length = labels.length
	const days = dateRange.value ? Math.max(1, (dateRange.value[1] - dateRange.value[0]) / 86400000 + 1) : 1
	const values = Array.from({ length }, () =>
		Math.round(200 + Math.random() * 300 + days * 5)
	)

	return {
		title: {
			text: `${areaType.value}维度 ${activeType.value}能耗（${days}天）`,
			left: 'center'
		},
		tooltip: { trigger: 'axis' },
		xAxis: { type: 'category', data: labels },
		yAxis: { type: 'value' },
		series: [
			{
				name: activeType.value,
				type: 'bar',
				data: values,
				barWidth: '40%'
			}
		]
	}
})

// Excel 导出
function exportExcel() {
	const labels = areaLabels[areaType.value]
	const values = chartOptions.value.series[0].data
	const rows = [['区域', '用量']]
	for (let i = 0; i < labels.length; i++) {
		rows.push([labels[i], values[i]])
	}
	const ws = XLSX.utils.aoa_to_sheet(rows)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, '区域报表')
	XLSX.writeFile(wb, `${areaType.value}_${activeType.value}_报表.xlsx`)
}

// PNG 图片导出
function exportImage() {
	const el = chartRef.value?.$el
	if (!el) return
	html2canvas(el).then((canvas) => {
		const link = document.createElement('a')
		link.href = canvas.toDataURL()
		link.download = `${areaType.value}_${activeType.value}_图表.png`
		link.click()
	}).catch(() => {
		ElMessage.error('导出失败，请重试')
	})
}
</script>

<style scoped>
.toolbar {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
	gap: 10px;
}
</style>
